package com.xinongbest.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinongbest.mall.common.Constant;
import com.xinongbest.mall.exception.ImoocMallException;
import com.xinongbest.mall.exception.ImoocMallExceptionEnum;
import com.xinongbest.mall.model.dao.ProductMapper;
import com.xinongbest.mall.model.dto.ProductAddDto;
import com.xinongbest.mall.model.dto.ProductRequestDto;
import com.xinongbest.mall.model.pojo.Product;
import com.xinongbest.mall.model.query.ProductListQuery;
import com.xinongbest.mall.model.vo.CategoryVo;
import com.xinongbest.mall.service.CategoryService;
import com.xinongbest.mall.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    ProductMapper productMapper;

    @Autowired
    CategoryService categoryService;

    @Override
    public void add(ProductAddDto productAddDto) {
        Product product = productMapper.selectByName(productAddDto.getName());
        if (product != null) {
            throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTED);
        }
        Product productAdd = new Product();
        BeanUtils.copyProperties(productAddDto, productAdd);
        int count = productMapper.insert(productAdd);
        if (count == 0) {
            throw new ImoocMallException(ImoocMallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public String uploadImage(HttpServletRequest servletRequest, MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 目录
        File fileDir = new File(Constant.FILE_UPLOAD_DIR);
        if (!fileDir.exists()) {
            if (!fileDir.mkdir()) {
                throw new ImoocMallException(ImoocMallExceptionEnum.MAKE_DIR_FIELD);
            }
        }
        // 生成UUID
        UUID uuid = UUID.randomUUID();
        String newFileName = uuid.toString() + suffix;
        File newFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String uploadPath;
        try {
            uploadPath = getHost(new URI(servletRequest.getRequestURL() + "")) + "/images" + newFileName;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            uploadPath = null;
        }
        return uploadPath;
    }

    /**
     * 获取请求地址信息
     *
     * @param uri
     * @return
     */
    private URI getHost(URI uri) {
        URI uriInfo;
        try {
            uriInfo = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
        } catch (URISyntaxException e) {
            uriInfo = null;
        }
        return uriInfo;
    }

    @Override
    public int batchUpdateSellStatus(Integer[] ids, Integer sellStatus) {
        return productMapper.batchUpdateSellStatus(ids, sellStatus);
    }

    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = productMapper.selectListForAdmin();
        return new PageInfo<>(products);
    }

    @Override
    public Product detail(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo selectList(ProductRequestDto requestDto) {
        ProductListQuery query = new ProductListQuery();
        if (!StringUtils.isEmpty(requestDto.getKeywords())) {
            String keywords = new StringBuilder("%").append(requestDto.getKeywords()).append("%").toString();
            query.setKeywords(keywords);
        }
        Integer categoryId = requestDto.getCategoryId();
        if (categoryId != null) {
            List<CategoryVo> categoryVos = categoryService.listForConsumer(categoryId);
            List<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(categoryId);
            if (!CollectionUtils.isEmpty(categoryVos)) {
                getCategoryIds(categoryVos, categoryIds);
            }
        }
        String orderBy = requestDto.getOrderBy();
        if (Constant.ProductListOrderBy.PRICE_DESC_ASC.contains(orderBy)) {
            PageHelper.startPage(requestDto.getPageNum(), requestDto.getPageSize(), orderBy);
        } else {
            PageHelper.startPage(requestDto.getPageNum(), requestDto.getPageSize());
        }
        List<Product> products = productMapper.selectList(query);
        return new PageInfo<>(products);
    }

    /**
     * 获取分类节点所有子节点的分类ID
     *
     * @param categoryVos
     * @param categoryIds
     */
    private void getCategoryIds(List<CategoryVo> categoryVos, List<Integer> categoryIds) {
        for (CategoryVo categoryVo : categoryVos) {
            if (categoryVo != null) {
                categoryIds.add(categoryVo.getId());
                getCategoryIds(categoryVo.getChildCategory(), categoryIds);
            }
        }

    }

}
